"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;
var _react = _interopRequireWildcard(require("react"));
var _reactDom = _interopRequireDefault(require("react-dom"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _tweenFunctions = _interopRequireDefault(require("tween-functions"));
var _raf = _interopRequireDefault(require("raf"));
var _EventDispatcher = _interopRequireDefault(require("./EventDispatcher"));
var _util = require("./util");
var _excluded = ["component", "onClick", "duration", "active", "showHeightActive", "ease", "toShowHeight", "offsetTop", "targetId", "to", "toHash", "componentProps"];
function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { "default": e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n["default"] = e, t && t.set(e, n), n; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? Object(arguments[r]) : {}, o = Object.keys(t); "function" == typeof Object.getOwnPropertySymbols && o.push.apply(o, Object.getOwnPropertySymbols(t).filter(function (e) { return Object.getOwnPropertyDescriptor(t, e).enumerable; })), o.forEach(function (r) { _defineProperty(e, r, t[r]); }); } return e; }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var s = Object.getOwnPropertySymbols(e); for (r = 0; r < s.length; r++) o = s[r], t.includes(o) || {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (e.includes(n)) continue; t[n] = r[n]; } return t; }
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
function _possibleConstructorReturn(t, e) { if (e && ("object" == typeof e || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); }
function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); }
function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); }
function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /**
 * Created by jljsj on 16/1/13.
 */
var scrollLinkLists = [];
var ScrollLink = /*#__PURE__*/function (_React$Component) {
  function ScrollLink(props) {
    var _this;
    _classCallCheck(this, ScrollLink);
    _this = _callSuper(this, ScrollLink, [props]);
    _defineProperty(_this, "onClick", function (e) {
      e.preventDefault();
      _EventDispatcher["default"].removeAllType('scroll.scrollAnchorEvent');
      _this.elementDom = document.getElementById(_this.props.to);
      ;
      if (_this.rafID !== -1 || !_this.elementDom) {
        return;
      }
      _this.scrollTop = _this.target ? _this.target.scrollTop : (0, _util.currentScrollTop)();
      _this.initTime = Date.now();
      _this.rafID = (0, _raf["default"])(_this.raf);
      scrollLinkLists.forEach(function (item) {
        if (item !== _this) {
          item.remActive();
        }
      });
      _this.addActive();
    });
    _defineProperty(_this, "getToTop", function () {
      var elementRect = _this.elementDom && _this.elementDom.getBoundingClientRect();
      _this.clientHeight = _this.target ? _this.target.clientHeight : (0, _util.windowHeight)();
      var targetTop = _this.target ? _this.target.getBoundingClientRect().top : 0;
      var toTop = Math.round(elementRect.top + (0, _util.currentScrollTop)()) - _this.props.offsetTop - targetTop;
      var t = (0, _util.transformArguments)(_this.props.showHeightActive)[0];
      var toShow = t.match('%') ? _this.clientHeight * parseFloat(t) / 100 : t;
      return _this.props.toShowHeight ? toTop - toShow + 0.5 : toTop;
    });
    _defineProperty(_this, "cancelRequestAnimationFrame", function () {
      _raf["default"].cancel(_this.rafID);
      _this.rafID = -1;
    });
    _defineProperty(_this, "addActive", function () {
      if (!_this.state.active) {
        var obj = {
          target: _this.dom,
          to: _this.props.to
        };
        _this.props.onFocus(obj);
        _this.setState({
          active: true
        }, function () {
          if (_this.props.toHash) {
            var link = "#".concat(_this.props.to);
            history.pushState(null, window.title, link); // eslint-disable-line
          }
        });
      }
    });
    _defineProperty(_this, "raf", function () {
      if (_this.rafID === -1) {
        return;
      }
      var duration = _this.props.duration;
      var now = Date.now();
      var progressTime = now - _this.initTime > duration ? duration : now - _this.initTime;
      // 动画时也会改变高度，动态获取
      var easeValue = _tweenFunctions["default"][_this.props.ease](progressTime, _this.scrollTop, _this.getToTop(), duration);
      if (_this.target) {
        _this.target.scrollTop = easeValue;
      } else {
        window.scrollTo(window.scrollX, easeValue);
      }
      if (progressTime === duration) {
        _this.elementDom = null;
        _this.cancelRequestAnimationFrame();
        _EventDispatcher["default"].reAllType('scroll.scrollAnchorEvent');
      } else {
        _this.rafID = (0, _raf["default"])(_this.raf);
      }
    });
    _defineProperty(_this, "remActive", function () {
      if (_this.state.active) {
        var obj = {
          target: _this.dom,
          to: _this.props.to
        };
        _this.props.onBlur(obj);
        _this.setState({
          active: false
        });
      }
    });
    _defineProperty(_this, "scrollEventListener", function () {
      var elementDom = document.getElementById(_this.props.to);
      if (!elementDom) {
        return;
      }
      // 滚动时会改变高度, 动态获取高度
      var clientHeight = _this.target ? _this.target.clientHeight : (0, _util.windowHeight)();
      var elementRect = elementDom.getBoundingClientRect();
      var elementClientHeight = elementDom.clientHeight;
      var targetTop = _this.target ? _this.target.getBoundingClientRect().top : 0;
      var top = Math.round(-elementRect.top + targetTop);
      var showHeightActive = (0, _util.transformArguments)(_this.props.showHeightActive);
      var startShowHeight = showHeightActive[0].toString().indexOf('%') >= 0 ? parseFloat(showHeightActive[0]) / 100 * clientHeight : parseFloat(showHeightActive[0]);
      var endShowHeight = showHeightActive[1].toString().indexOf('%') >= 0 ? parseFloat(showHeightActive[1]) / 100 * clientHeight : parseFloat(showHeightActive[1]);
      if (top >= Math.round(-startShowHeight) && top < Math.round(elementClientHeight - endShowHeight)) {
        _this.addActive();
      } else {
        _this.remActive();
      }
    });
    _this.rafID = -1;
    _this.state = {
      active: false
    };
    return _this;
  }
  _inherits(ScrollLink, _React$Component);
  return _createClass(ScrollLink, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      var _this2 = this;
      this.dom = _reactDom["default"].findDOMNode(this);
      this.target = this.props.targetId && document.getElementById(this.props.targetId);
      scrollLinkLists.push(this);
      var date = Date.now();
      var length = _EventDispatcher["default"]._listeners.scroll ? _EventDispatcher["default"]._listeners.scroll.length : 0;
      this.eventType = "scroll.scrollAnchorEvent".concat(date).concat(length);
      _EventDispatcher["default"].addEventListener(this.eventType, this.scrollEventListener, this.target);
      // 第一次进入；等全部渲染完成后执行;
      setTimeout(function () {
        _this2.scrollEventListener();
      });
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      var _this3 = this;
      scrollLinkLists = scrollLinkLists.filter(function (item) {
        return item !== _this3;
      });
      _EventDispatcher["default"].removeEventListener(this.eventType, this.scrollEventListener, this.target);
      this.cancelRequestAnimationFrame();
    }
  }, {
    key: "render",
    value: function render() {
      var _this4 = this;
      var _this$props = this.props,
        component = _this$props.component,
        onClick = _this$props.onClick,
        duration = _this$props.duration,
        tagActive = _this$props.active,
        showHeightActive = _this$props.showHeightActive,
        ease = _this$props.ease,
        toShowHeight = _this$props.toShowHeight,
        offsetTop = _this$props.offsetTop,
        targetId = _this$props.targetId,
        to = _this$props.to,
        toHash = _this$props.toHash,
        componentProps = _this$props.componentProps,
        props = _objectWithoutProperties(_this$props, _excluded);
      var active = this.state.active ? tagActive : '';
      props.onClick = function (e) {
        onClick(e);
        _this4.onClick(e);
      };
      var reg = new RegExp(active, 'ig');
      var className = props.className || '';
      props.className = className.indexOf(active) === -1 ? "".concat(className, " ").concat(active).trim() : className.replace(reg, '').trim();
      return /*#__PURE__*/(0, _react.createElement)(this.props.component, _objectSpread({}, props, componentProps));
    }
  }]);
}(_react["default"].Component);
_defineProperty(ScrollLink, "propTypes", {
  component: _propTypes["default"].any,
  children: _propTypes["default"].any,
  className: _propTypes["default"].string,
  style: _propTypes["default"].any,
  offsetTop: _propTypes["default"].number,
  duration: _propTypes["default"].number,
  active: _propTypes["default"].string,
  to: _propTypes["default"].string,
  targetId: _propTypes["default"].string,
  showHeightActive: _propTypes["default"].any,
  toShowHeight: _propTypes["default"].bool,
  ease: _propTypes["default"].string,
  onClick: _propTypes["default"].func,
  onFocus: _propTypes["default"].func,
  onBlur: _propTypes["default"].func,
  toHash: _propTypes["default"].bool,
  componentProps: _propTypes["default"].object
});
_defineProperty(ScrollLink, "defaultProps", {
  component: 'div',
  offsetTop: 0,
  duration: 450,
  active: 'active',
  showHeightActive: '50%',
  ease: 'easeInOutQuad',
  toHash: false,
  onClick: _util.noop,
  onFocus: _util.noop,
  onBlur: _util.noop,
  componentProps: {}
});
ScrollLink.isScrollLink = true;
var _default = exports["default"] = ScrollLink;